<?php
/**
 * 微信支付通用类
 * User: H2H
 * Date: 2018/9/21
 * Time: 14:27
 */

namespace app\api\controller\wechat;


class work
{
    public static $instance;

    private function __construct($config = [])
    {
        empty($config['key']) or $this->key = $config['key'];
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    /**
     * 获取实例
     * @param array $config
     * @return work
     */
    public static function instance($config = [])
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * 数组转url参数格式
     * @param $array
     * @return string
     */
    public function arrayToUrl($array)
    {
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 数组转xml
     * @param $array
     * @return string
     */
    public function arrayToXml($array)
    {
        $xml = "<xml>";
        foreach ($array as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * xml转对象
     * @param $xml
     * @return \SimpleXMLElement
     */
    public function xmlToOjb($xml)
    {
        return simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
    }

    /**
     * 根据参数进行签名计算
     * @param $array
     * @param string $key
     * @return string
     */
    public function makeSign($array, $key = '')
    {
        if (empty($this->key) && empty($key) ) return '请传入config[key]';

        $key = !empty($key) ? $key : $this->key;

        ksort($array);

        $signStr = $this->arrayToUrl($array);
        $signStr .= "&key=" . $key;

        return strtoupper(md5($signStr));
    }
}